package kin.system.security;



import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import kin.bean.security.User;

import kin.service.security.UserServiceManager;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;


import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/*import com.huaxin.bean.Users;
import com.huaxin.dao.UsersDao;*/

/*
 * 
 * UsernamePasswordAuthenticationFilter源码
	attemptAuthentication
		this.getAuthenticationManager()
			ProviderManager.java
				authenticate(UsernamePasswordAuthenticationToken authRequest)
					AbstractUserDetailsAuthenticationProvider.java
						authenticate(Authentication authentication)
							P155 user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
								DaoAuthenticationProvider.java
									P86 loadUserByUsername
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
	public static final String VALIDATE_CODE = "validateCode"; 
	
	//DaoAuthenticationProvider
	
	
	
	@Inject
	private UserServiceManager userServiceManager;
	//private UsersDao usersDao;
	 
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		if ( !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
this.setUsernameParameter("username");
this.setPasswordParameter("password");
System.out.println("PasswordParameter"+this.getPasswordParameter());
        String username = obtainUsername(request);
        String password = obtainPassword(request);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }
                  
        username = username.trim();
	
		

        System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication--bef-----username:"+ this.getUsernameParameter());
		User user=this.userServiceManager.findByUsername(username);
		//Users users = this.usersDao.findByName(username);
		System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication--after-----username:"+user.getUsername());
		if(user == null || !user.getPassword().equals(password)) {
			System.out.println("-----------exception:");
	/*
	          在我们配置的simpleUrlAuthenticationFailureHandler处理登录失败的处理类在这么一段
	    这样我们可以在登录失败后，向用户提供相应的信息。
		if (forwardToDestination) {
            request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
        } else {
            HttpSession session = request.getSession(false);

            if (session != null || allowSessionCreation) {
                request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
            }
        }
	 */
			throw new AuthenticationServiceException("用户名或者密码错误！"); 
		}
			System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication.username:"+username);
			System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication.password:"+password);
			//password="";
		
		//UsernamePasswordAuthenticationToken实现 Authentication
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
		//authRequest.setAuthenticated(true);
		System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication.authRequest:"+authRequest.getDetails());
		System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication.authRequest:"+authRequest.getCredentials());
		System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication.authRequest:"+authRequest.getName());
		for(GrantedAuthority ga:authRequest.getAuthorities()){
			System.out.println("---------GrantedAuthority:"+ga.getAuthority());
		}
		// Place the last username attempted into HttpSession for views
		System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication.getPrincipal:"+authRequest.getPrincipal());
		// 允许子类设置详细属性
		
		/*HttpSession session=request.getSession(false);
		if(session!=null||getAllowSessionCreation()){
			request.getSession().setAttribute(SPRING_SECURITY_FORM_USERNAME_KEY,TextEscapeUtils.escapeEntities(username));
			}*/
		this.setDetails(request, authRequest);
		 System.out.println("-----------MyUsernamePasswordAuthenticationFilter.attemptAuthentication.authRequest:after:"+authRequest.getDetails());
		 
	        // 运行UserDetailsService的loadUserByUsername 再次封装Authentication
		return getAuthenticationManager().authenticate(authRequest);
	}

public UserServiceManager getUserServiceManager() {
	return userServiceManager;
}

public void setUserServiceManager(UserServiceManager userServiceManager) {
	this.userServiceManager = userServiceManager;
}
	


	/*protected void checkValidateCode(HttpServletRequest request) { 
		HttpSession session = request.getSession();
		
	    String sessionValidateCode = obtainSessionValidateCode(session); 
	    //让上一次的验证码失效
	    session.setAttribute(VALIDATE_CODE, null);
	    String validateCodeParameter = obtainValidateCodeParameter(request);  
	    if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {  
	        throw new AuthenticationServiceException("验证码错误！");  
	    }  
	}
	
	private String obtainValidateCodeParameter(HttpServletRequest request) {
		Object obj = request.getParameter(VALIDATE_CODE);
		return null == obj ? "" : obj.toString();
	}

	protected String obtainSessionValidateCode(HttpSession session) {
		Object obj = session.getAttribute(VALIDATE_CODE);
		return null == obj ? "" : obj.toString();
	}

	
*/

	
	
	
}

